#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys


def resolve_proto_file():
    """根据proto文件生成pb2.py文件"""
    lib = os.path.abspath(os.path.dirname(__file__))
    former_pb = os.path.join(lib, "AMessage_pb2.py")

    # 删除旧的pb文件
    if os.path.exists(former_pb):
        os.remove(former_pb)

    # 如果是windows os
    if os.name == "nt":
        protoc = os.path.join(lib, "protoc-3.7.1-win64", "bin")
    # 如果是linux os
    else:
        protoc = os.path.join(lib, "protoc-3.7.1-linux-ppcle_64", "bin")
    # 切换目录
    sys.path.append(protoc)

    # 运行protoc解析proto文件
    result = os.system('protoc --python_out=. AMessage.proto')
    if result == 0:
        print("解析proto文件成功")
    else:
        raise RuntimeError("解析proto文件失败")


def install_libs():
    """安装依赖库"""
    lib = os.path.abspath(os.path.dirname(__file__))

    # 如果是windows os
    if os.name == "nt":
        protobuf = os.path.join(lib, "protobuf-3.7.1-cp36-cp36m-win_amd64.whl")
    # 如果是linux os
    else:
        protobuf = os.path.join(lib, "protobuf-3.7.1-cp36-cp36m-manylinux1_x86_64.whl")

    # 运行pip命令进行安装
    result = os.system('python3 -m pip install {}'.format(protobuf))
    if result == 0:
        print("第三方库安装成功")
    else:
        raise RuntimeError("第三方库安装失败")


if __name__ == "__main__":
    resolve_proto_file()
    install_libs()
